import { Ref, ref } from 'vue'

import { IListResult } from '@/http/types/base'

type PaginationFunc<T, K> = (params: K) => Promise<IListResult<T>>
export default function usePagination<T, K extends Object>(
  pagedFunction: PaginationFunc<T, K>,
  params: Ref<K>,
  defaultSort: string = '',
) {
  const DEFAULT_SORT = defaultSort || ''
  const isLoading = ref(false)
  const sort = ref(DEFAULT_SORT)
  const tableData = ref<Array<T>>([]) as Ref<T[]>

  const getTableData = async () => {
    isLoading.value = true
    const res = await pagedFunction({
      sorting: sort.value,
      ...params.value,
    }).finally(() => {
      isLoading.value = false
    })
    tableData.value = res.items
  }

  const handleSortChange = ({ prop, order }: any) => {
    let sortStr
    if (order === 'descending') {
      sortStr = `${prop} desc`
    } else if (order === 'ascending') {
      sortStr = `${prop} asc`
    } else {
      sortStr = DEFAULT_SORT
    }
    sort.value = sortStr
    getTableData()
  }

  return {
    tableData,
    isLoading,
    sort,
    getTableData,
    handleSortChange,
  }
}
